<!DOCTYPE html >
<html>
    <head>
        <link rel="stylesheet" href="{{ urlAssetsBundle }}/bootstrap/3.3.7/css/bootstrap.min.css">
        <link rel="stylesheet" href="{{ urlAssetsBundle }}/bootstrap/fileinput/css/fileinput.min.css" >
        <link rel="stylesheet" href="{{ urlAssetsCss }}/admin/images/crop.css">
        <link rel="stylesheet" href="/assets/jcrop/css/jquery.Jcrop.min.css">
        <link rel="stylesheet" href="{{ urlAssetsBundle }}/bootstrap/toastr/toastr.min.css">
        <link rel="stylesheet" href="{{ urlAssetsCss }}/admin/base.css">
        <style>
          
        </style>
    </head>
    <body class="wrap">
        <div class="upload-wrap">
            <div class="col-xs-12 images-upload" style="display:block;" id="upload">
                 <input type="file"  id="imageUpload" multiple class="file" name="images">
            </div>
            <div class="col-xs-12 text-center operate" id="uploadBtn" style="display:block;">
                <a href="/admin/images/index/pid/{{ id }}" class="btn btn-sm btn-success">确定</a>
                <a href="#" class="btn btn-default btn-sm" id="cropImage" >裁剪图片</a>
                <a href="/admin/images/index/pid/{{ id }}" class="btn btn-sm btn-default">取消</a>
            </div>  
        </div>
        <div class="crop-wrap" style="display:none;">
            <div class="image-crop" id="crop">
                <label class="original-label">原图</label>
                <img class="original-image" src="/assets/jcrop/demos/demo_files/pool.jpg" id="pic" >
                <label class="big-label">大图示例（400*400）</label>
                <div class="big-preview-pane preview-pane">
                    <div class="preview-container">
                      <img src="/assets/jcrop/demos/demo_files/pool.jpg" class="jcrop-preview" alt="Preview" />
                    </div>
                </div>
                <label class="middle-label">中图示例（220*220）</label>
                <div class="middle-preview-pane preview-pane">
                    <div class="preview-container">
                      <img src="/assets/jcrop/demos/demo_files/pool.jpg" class="jcrop-preview" alt="Preview" />
                    </div>
                </div>
                <label class="small-label">小图示例（50*50）</label>
                <div class="small-preview-pane preview-pane">
                    <div class="preview-container">
                      <img src="/assets/jcrop/demos/demo_files/pool.jpg" class="jcrop-preview" alt="Preview" />
                    </div>
                </div>
        </div>
            <div class="col-xs-12 text-center operate" id="cropBtn" >
                <a href="#" class="btn btn-sm btn-success" id="confirmCrop">确定</a>
                <a href="#" class="btn btn-sm btn-default" id="cancelCrop">取消</a>
            </div>
        </div>
        
        
        <script src="{{ urlAssetsJs }}/jquery/jquery-1.11.1.min.js"></script>
        <script src="{{ urlAssetsBundle }}/bootstrap/fileinput/js/fileinput.js"></script>
        <script src="{{ urlAssetsBundle }}/bootstrap/fileinput/js/fileinput_locale_zh.js"></script>
        <script src="/assets/jcrop/js/jquery.Jcrop.min.js"></script>
        <script src="{{ urlAssetsBundle }}/bootstrap/toastr/toastr.min.js"></script>
        <script>
        var imageUpload = $( '#imageUpload' );
    $( '#cropImage' ).click( function(){ 
        if( selected === null )
        {
            toastr.error( '请选择图片' );
            return false;
        }
        var filestack = imageUpload.data( 'fileinput').filestack; //上传的图片
        if( filestack.length )
        {
            var url = window.URL.createObjectURL( filestack[selected]); //对上传图片
        }
        else
        {
            toastr.error( '请选择上传的图片' );
            return false;
        }
        $( '.upload-wrap' ).hide();
        $( '.crop-wrap' ).show().find( '.image-crop img' ).attr( 'src', url );
        cropImage();
    });

    //取消裁剪
    $( '#cancelCrop' ).click( function(){
        $( '.crop-wrap' ).hide();
        $( '.upload-wrap' ).show();
    });
    //生成裁剪
    $( '#confirmCrop' ).click( function(){
        var filestack = imageUpload.data( 'fileinput' ).filestack;
        if( parseInt( coords.w ) > 0 && filestack[ selected ] ) //截取的坐标
        {
            var imageData = new FormData();
            imageData.append( 'x', coords.x );
            imageData.append( 'y', coords.y );
            imageData.append( 'w', coords.w );
            imageData.append( 'h', coords.h );
            imageData.append( 'image', filestack[ selected ] );
            
            $.ajax( { url: '/admin/images/cropImage', data: imageData,  dataType: 'json', type: 'POST',
                processData: false, contentType:false,
                success: function( ret ){
                    if( ! ret.status )
                    {
                        //截取成功，就把参数给选中的图片
                        var sel = '.s' + selected;
                        $( sel + ' img').attr( { 'src': '/upload/crop.jpeg?' + Math.random() });
                        $( sel ) . data( 'coords', coords ).removeClass( 's' + selected ); //裁剪完成
                        $( '.crop-wrap' ).hide();
                        $( '.upload-wrap' ).show();
                    }
                    else
                    {
                        toastr.error( ret.msg );
                    }
            }});
        }
        else //请截图
        {
            toastr.error( '请选择截取区域' );
        }
    });
    //选中要截取的图片
     var selected = null;
    $( document.body ).on( 'click', '.file-preview-frame', function( e ){
        if( e.target.tagName !== "IMG")
        {
            return true;
        }
        var target = $( this );
        if( target.hasClass( 'selected')) 
        {
            target.removeClass( 'selected');
        }
        else
        {
            selected = target.attr( 'data-fileindex' );
            if( selected === '-1' ) //表示已经上传了
            {
                selected = null;
                toastr.error( '此图片不可裁剪' );
                return;
            }
            target.addClass( 'selected s' + selected ); //设置样式，方便查找
        }
    });   
 
    var coords = { x:0, y:0, w:400, h:400 }; //裁剪坐标，默认坐标
    var preview = {  "big":{}, "middle":{},"small":{} };//生成大，中，小的示例图
    function createPreview() 
    {
        for( var type in preview )
        {
            var sel = '.' + type + '-preview-pane';
            var obj = {};
            obj.view = $( sel );
            obj.x = $( sel + ' .preview-container' ).width();
            obj.y = $( sel + ' .preview-container' ).height();
            obj.img = $( sel + ' .preview-container img' );
            preview[ type ] = obj;
        }
    }
    createPreview();
    var jcrop_api,boundx, boundy;
    function cropImage() {
        if( jcrop_api ) //已经存在了，把以前的删除
        {
            jcrop_api.destroy();
            $( '#pic' ).css( 'height', 'auto');
        }
       $('#pic').Jcrop({ //原图
            onChange: updatePreview,
            setSelect:[ 0,0,coords.w,coords.h ],
            aspectRatio: preview.big.x / preview.big.y
          },function(){
            // Use the API to get the real image size
              var bounds = this.getBounds();
              boundx = bounds[0];
              boundy = bounds[1];
              // Store the API in the jcrop_api variable
              jcrop_api = this;
              jcrop_api.setSelect( [ 0,0,coords.w,coords.h ] );
              // Move the preview into the jcrop container for css positioning
              for( var type in preview )
              {
                  preview[type].view.appendTo(jcrop_api.ui.holder);
              }
        });
        
    }
    function updatePreview(c)
    {
        if( parseInt(c.w) > 0 )
        {
            for( var type in preview )   
            {
                var rx = preview[type].x / c.w;
                var ry = preview[type].y / c.h;
                preview[type].img.css({
                  width: Math.round(rx * boundx) + 'px',
                  height: Math.round(ry * boundy) + 'px',
                  marginLeft: '-' + Math.round(rx * c.x) + 'px',
                  marginTop: '-' + Math.round(ry * c.y) + 'px'
                });
            }
          coords = c;
        }
    };
    imageUpload.fileinput({
           showCaption: false,
           showPreview: true,
           allowedFileExtensions : ['jpg', 'png','gif', 'jpeg'],
           browseClass: "btn btn-primary btn-sm",
           uploadClass: "btn btn-default btn-sm",
           removeClass: "btn btn-default btn-sm",
           uploadUrl: "/admin/images/saveImage",
           language: "zh",
           maxFileCount: 10,
           overwriteInitial: true,
           uploadAsync: true,
           uploadExtraData: {
               pid: "{{ id }}"
           }
       });
       
   
    var cnt = 0; //自动变换高度
    imageUpload.on('fileloaded', function(event, file, previewId, index) {
       ++cnt;
       if( cnt > 5 )
       {
           $( '.images' ).css( 'height', '550' );
       }
       else if( cnt > 10 )
       {
            $( '.images' ).css( 'height', '750' );
       }
   });
   //上传前传递截取参数
    imageUpload.on( 'filepreajax', function( event, previewId, index ){
        var coords = $( '#' + previewId ).data( 'coords');
        var self = imageUpload.data( 'fileinput' );
        if( coords )
        {
            self.formdata.append( 'x', coords.x );
            self.formdata.append( 'y', coords.y );
            self.formdata.append( 'w', coords.w );
            self.formdata.append( 'h', coords.h );      
        }
   });
        </script>
    </body>
</html>